
const db = require("../database/models");
const Seedling_common = db.seedling_common;
const Op = db.Sequelize.Op;

const Seedling_buy = db.seedling_buy;
const Seedling_self = db.seedling_self;
Seedling_common.hasMany(Seedling_buy,{
  foreignKey:'code',
  sourceKey:'code',
  onDelete:'CASCADE',
  onUpdate:'CASCADE'
});
Seedling_common.hasMany(Seedling_self,{
  foreignKey:'code',
  sourceKey:'code',
  onDelete:'CASCADE',
  onUpdate:'CASCADE'
});

// Retrieve all from the database.
exports.findAll = (req, res) => {
  const offset = req.query.offset?parseInt(req.query.offset):0;
  const limit = req.query.limit?parseInt(req.query.limit):10;
  const all = req.query.mode==='all'?true:false;
  const hiden = req.query.mode==='hiden'?true:false;
  const mode = all||hiden?false:true;
  const condition = hiden
  ?{
    'deletedAt':{
      [Op.not]:null
    }  
  }
  :{};

  Seedling_common.findAndCountAll({
     offset: offset, limit: limit ,paranoid:mode,where:condition,
     include:[{
       model:Seedling_buy
     },{
      model:Seedling_self
     }
    ]
    })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving seedling_common."
      });
    });
  
};

// Retrieve a single one with attr and value
exports.findByAttr = (req, res) => {
  const offset = req.query.offset?parseInt(req.query.offset):0;
  const limit = req.query.limit?parseInt(req.query.limit):10;
  const all = req.query.mode==='all'?true:false;
  const hiden = req.query.mode==='hiden'?true:false;
  const mode = all||hiden?false:true;

  const attr = req.params.attr;
  const value = req.params.value;
  const condition = {};
  condition[attr]=value;
  if(!all){
    condition['deletedAt']=hiden
    ?{
        [Op.not]:null 
    }
    :null;
  };
  Seedling_common.findAndCountAll({ 
    where: condition , offset:offset,limit:limit,paranoid:mode,
    include:[{
      model:Seedling_buy
    },{
     model:Seedling_self
    }
   ]
  }).then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving seedling_common."
      });
    });
  
};

// Find a single one with an id
exports.findOne = (req, res) => {
    const id = req.params.id;
    const mode = req.query.mode=='all'?false:true;

    Seedling_common.findByPk(id,
      {
        paranoid:mode,
        include:[{
          model:Seedling_buy
        },{
         model:Seedling_self
        }
       ]
     })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message: "Error retrieving Seedling_common with id=" + id
        });
      });
  
};